package com.h4313.ghome.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class NetworkHelper {

	static String downloadUrl(String myurl, Integer connectTO, Integer readTO)
			throws IOException {
		return downloadUrl(myurl, connectTO, readTO, "GET", "");
	}

	static String downloadUrl(String myurl, Integer connectTO, Integer readTO,
			String method, String payload) throws IOException {

		InputStream is = null;

		String contentAsString = "";

		// configuration de la connection
		URL url = new URL(myurl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(readTO);
		conn.setConnectTimeout(connectTO);
		conn.setRequestMethod(method);
		conn.setDoInput(true);

		// On commence à faire des requetes
		conn.connect();
		int response = conn.getResponseCode();
		Log.d("Margot ", "the response is" + response);
		is = conn.getInputStream();

		// Conversion de l'InputStream en String
		contentAsString = readIt(is);

		if (is != null)
			is.close();

		return contentAsString;

	}

	static String readIt(InputStream stream) throws IOException,
			UnsupportedEncodingException {
		
		StringWriter writer = new StringWriter();
		InputStreamReader streamReader = new InputStreamReader(stream);
		
		// le buffer permet le readline
		BufferedReader buffer = new BufferedReader(streamReader);
		String line = "";
		while (null != (line = buffer.readLine())) {
			writer.write(line);
		}
		// Sortie finale dans le String
		return writer.toString();
	}

}
